//
//  WXMWebViewController.m
//  WebDemo
//
//  Created by lanou on 15/12/12.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import <WebKit/WebKit.h>
#import "WXMWebViewController.h"



#define IOS8x ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
#define WebViewNav_TintColor ([UIColor orangeColor])

@interface WXMWebViewController ()<UIWebViewDelegate,UIActionSheetDelegate,WKNavigationDelegate>

@property (nonatomic, assign)NSUInteger loadCount;
@property (nonatomic, strong)UIProgressView *proGressView;
@property (nonatomic, strong)UIWebView *webView;
@property (nonatomic, strong)WKWebView *wkWebView;




@end

@implementation WXMWebViewController


/* 传人控制器.url.标题*/
+ (void)showWithController:(UIViewController *)controller withUrlStr:(NSString *)urlStr withTitle:(NSString *)title {
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    WXMWebViewController *webController = [WXMWebViewController new];
    webController.homeUrl = [NSURL URLWithString:urlStr];
    webController.title = title;
    [controller.navigationController pushViewController:webController animated:YES];
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    [self configUI];
    [self configBackItem];
    [self configMenuItem];
    
    // Do any additional setup after loading the view.
}

- (void)configUI {
    //进度条
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
    progressView.tintColor = kBackGroundColor;
    [self.view addSubview:progressView];
    self.proGressView = progressView;
    
    //网页
    if (IOS8x) {
        WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        wkWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        wkWebView.backgroundColor = [UIColor whiteColor];
        wkWebView.navigationDelegate = self;
        [self.view insertSubview:wkWebView belowSubview:progressView];
        [wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:(NSKeyValueObservingOptionNew) context:nil];
        NSURLRequest *request = [NSURLRequest requestWithURL:_homeUrl];
        [wkWebView loadRequest:request];
        self.wkWebView = wkWebView;
        
    }else {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        webView.scalesPageToFit = YES;
        webView.backgroundColor = [UIColor whiteColor];
        webView.delegate = self;
        [self.view insertSubview:webView belowSubview:progressView];
        NSURLRequest *request = [NSURLRequest requestWithURL:_homeUrl];
        [webView loadRequest:request];
        self.webView = webView;
        
    }
}

- (void)configBackItem {
    //导航栏的返回按钮

    UIImage *backImage = [[UIImage imageNamed:@"web_back@2x"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [backBtn setTintColor:[UIColor whiteColor]];
    [backBtn setBackgroundImage:backImage forState:(UIControlStateNormal)];
    
    [backBtn addTarget:self action:@selector(backBtnPressed:) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = closeItem;
   

}

- (void)configMenuItem {
    //导航栏菜单按钮
    UIImage *menuImage= [[UIImage imageNamed:@"cc_webview_menu"] imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
    UIButton *menuBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 20)];
    [menuBtn setTintColor:[UIColor whiteColor]];
    [menuBtn setBackgroundImage:menuImage forState:(UIControlStateNormal)];
    [menuBtn addTarget:self action:@selector(menuBtnPressed:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc]initWithCustomView:menuBtn];
    self.navigationItem.rightBarButtonItem = menuItem;
    
}


- (void)configCloseItem {
    //导航栏的关闭按钮
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [closeBtn setTitle:@"关闭" forState:(UIControlStateNormal)];
    [closeBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [closeBtn addTarget:self action:@selector(colseBtnPressed:) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
    NSMutableArray *newArr = [NSMutableArray arrayWithObjects:self.navigationItem.leftBarButtonItem, closeItem, nil];
    self.navigationItem.leftBarButtonItems = newArr;
    
}


#pragma mark -
#pragma mark ---普通按钮事件---

//返回按钮事件
- (void)backBtnPressed: (id)sender {
    if (IOS8x) {
        if (self.wkWebView.canGoBack) {
            [self.wkWebView goBack];
            if (self.navigationItem.leftBarButtonItems.count == 1) {
                [self configCloseItem];
            }
        }else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else {
        if (self.webView.canGoBack) {
            [self.webView goBack];
            if (self.navigationItem.leftBarButtonItems.count ==1) {
                [self configCloseItem];
            }
        }else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

//菜单按钮点击
- (void)menuBtnPressed:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"safari打开",@"复制链接",@"分享",@"刷新", nil];
    [actionSheet showInView:self.view];
    
}

//关闭按钮事件
- (void)colseBtnPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark ---菜单按钮事件---

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    NSString *urlStr = _homeUrl.absoluteString;
    if (IOS8x) {
        urlStr = self.wkWebView.URL.absoluteString;
    }else {
        urlStr = self.webView.request.URL.absoluteString;
    }
    switch (buttonIndex) {
        case 0:
            //safari打开
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlStr]];
            break;
        case 1:
            //复制连接
            if (urlStr.length > 0) {
                [[UIPasteboard generalPasteboard]setString:urlStr];
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@""@"已复制链接到黏贴板" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
                [alertView show];
            }
            
            break;
        case 2:
            //分享
            
            break;
            
        case 3:
            //刷新
            if (IOS8x) {
                [self.wkWebView reload];
            }else {
                [self.webView reload];
            }
            
            break;
            
        default:
            break;
    }
    
    
}


#pragma mark -
#pragma mark ---wkWebView代理---

//如果不添加这个,那么wkwebview跳转不了AppStore

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"]) {
        [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

//计算wkwebView进度条

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if (object == self.wkWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newProgress = [[change objectForKey:NSKeyValueChangeNewKey]doubleValue];
        if (newProgress == 1) {
            self.proGressView.hidden = YES;
            [self.proGressView setProgress:0 animated:NO];
        }else {
            self.proGressView.hidden = NO;
            [self.proGressView setProgress:newProgress animated:YES];
            
        }
        
    }
    
}

//取消监听
- (void)dealloc {
    
    if (IOS8x) {
        [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    }
 
}

#pragma mark -
#pragma mark ---webView代理---

//计算webView进度条
- (void)setLoadCount:(NSUInteger)loadCount {
    _loadCount = loadCount;
    if (loadCount == 0) {
        self.proGressView.hidden = YES;
        [self.proGressView setProgress:0 animated:NO];
        
    }else {
        self.proGressView.hidden = NO;
        CGFloat oldP = self.proGressView.progress;
        CGFloat newP = (1.0 - oldP) / (loadCount + 1) + oldP;
        if ((newP > 0.95)) {
            newP = 0.95;
        }
        [self.proGressView setProgress:newP animated:YES];
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    self.loadCount ++;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.loadCount --;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    self.loadCount --;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
